package cn.itsource.pethome.service.impl;

import cn.itsource.pethome.domain.Department;
import cn.itsource.pethome.mapper.DepartmentMapper;
import cn.itsource.pethome.query.DepartmentQuery;
import cn.itsource.pethome.result.JSONResult;
import cn.itsource.pethome.result.PageList;
import cn.itsource.pethome.service.DepartmentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @description: service实现类
 * @auth: wujiangbo
 */
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService  {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public Department selectById(Long id) {
        return departmentMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageList<Department> pagelist(DepartmentQuery query) {
        Page<Department> page = PageHelper.startPage(query.getCurrent(), query.getSize());
        List<Department> resultList = departmentMapper.queryData(query);
        return new PageList(page.getTotal(), resultList);

    }

    @Override
    public List<Department> list() {
        DepartmentQuery query = new DepartmentQuery();
        List<Department> list = departmentMapper.queryData(query);
        return list;
    }

    @Override
    public JSONResult saveOrUpdate(Department dept) {
        if(dept.getId() != null){
            //编辑操作
            departmentMapper.updateByPrimaryKey(dept);
        }else{
            //新增操作
            departmentMapper.insert(dept);
        }
        return JSONResult.success();
    }

    @Override
    public JSONResult deleteBatch(DepartmentQuery departmentQuery) {
        for (Long id : departmentQuery.getIds()) {
           // departmentMapper.deleteByPrimaryKey(id);
            deleteDeptDeep(id);
        }

        return  JSONResult.success();
    }
    public void deleteDeptDeep(Long deptid){
        /**
         *
         * 递归删除
          1.找到parentId等于10的所有记录,list
         2.循环list,重复第一步
         3.如果没有子节点时删除自己
         */
        Example example = new Example(Department.class);
        example.and().andEqualTo("parentId",deptid);
        List<Department> list = departmentMapper.selectByExample(example);
        for (Department department : list) {
            Long id = department.getId();
            deleteDeptDeep(id);
        }
        departmentMapper.deleteByPrimaryKey(deptid);
    }
    //根据部门id删除部门信息,所有子节点所有字节点全部要删除
    @Override
    public JSONResult delete(Long id) {
        deleteDeptDeep(id);
        return JSONResult.success();
    }
}